<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/3/7
 * Time: 14:01
 */

namespace app\home\controller;

use  app\home\model\Coupon as CouponModel;
use app\home\model\UserCoupon;
use app\Request;
use think\cache\driver\Redis;

class Coupon
{
    /**
     * 优惠券列表
     */
    public function couponList(Request $request)
    {
        $param = $request->param();
        $limit = 10000;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $where[] = ['status', '=', 1];
        if (isset($param['classify_id']) && !empty($param['classify_id'])) {
            $where[] = ['classify_id', 'in', [0, $param['classify_id']]];
        }
        $where[] = ['end_time','>',time()];
        $couponModel = new CouponModel();
        $userCouponModel = new  UserCoupon();
        $userCoupon = $userCouponModel->where(['uid' => $request->userInfo['id']])->select()->toArray();
        $couponList = $couponModel->where($where)
            ->select()->toArray();
        $newUserCouponTime = 60 * 60 * 24 * 3;
        if ($couponList) {
            foreach ($couponList as $key => $value) {
                $couponList[$key]['end_time'] = date('Y-m-d H:i', $value['end_time']);
                $couponList[$key]['start_time'] = date('Y-m-d H:i', $value['start_time']);
                foreach ($userCoupon as $userCouponValue) {
                    // 此优惠券已经领取
                    if ($userCouponValue['coupon_id'] == $value['id'] && $userCouponValue['status'] == 1) {
                        unset($couponList[$key]);
                    }
                    // 领过的优惠券已经过期/或失效 且不能重复领取的优惠券
                    if ($userCouponValue['coupon_id'] == $value['id'] && $userCouponValue['status'] != 1 && $value['is_repeat'] == 0) {
                        unset($couponList[$key]);
                    }
                    if ($value['type'] == 2 && strtotime($request->userInfo['create_time']) + $newUserCouponTime < time()) {
                        unset($couponList[$key]);
                    }
                }
            }
        }
        $count = count($couponList);
        $couponList = array_splice($couponList, $start, $limit);
        return success('优惠券列表', ['list' => array_values($couponList), 'count' => $count]);
    }

    /**
     * @param Request $request
     *  领取优惠券
     */
    public function receiveCoupon(Request $request)
    {
        $param = $request->param();
        $userCouponModel = new  UserCoupon();
        foreach ($param['id'] as $value){
            $userCoupon = $userCouponModel->where([
                'uid' => $request->userInfo['id'],
                'coupon_id' => $value,
                'status' => 1,
            ])->find();
            if ($userCoupon) {
                return error($userCoupon['name'].'优惠券已领取');
            }
        }
        $couponModel = new CouponModel();
        $coupon = $couponModel->where('id','in' , $param['id'])->select()->toArray();
        $couponById = array_column($coupon,null,'id');
        $createTime = time();
        foreach ($param['id'] as $value){
            if ( $couponById[$value]['end_time']  < time()){
                 return error($couponById[$value]['name'].'已过期,请刷新');
            }
            $couponUserData[] = [
                'uid' => $request->userInfo['id'],
                'create_time' => $createTime,
                'coupon_id' => $value,
                'status' => 1,
                'effective_time' => $couponById[$value]['end_time'],
                'trigger_amount' =>  $couponById[$value]['trigger_amount'],
                'discount_intensity' =>  $couponById[$value]['discount_intensity'],
                'name' =>  $couponById[$value]['name'],
                'classify_id' =>  $couponById[$value]['classify_id'],
                'desc' =>  $couponById[$value]['desc'],
            ];
        }
        $userCouponModel->insertAll($couponUserData);
        $userModel = new \app\home\model\User();
        $userModel->where(['id' => $request->userInfo['id']])->inc('coupon_num',count($couponUserData))->update();

        return success('领取成功');
    }

    /**
     * 我的优惠券
     */
    public function myCoupon(Request $request)
    {
        $param = $request->param();
        $limit = 10;
        $start = 0;
        if (isset($param['limit']) && !empty($param['limit'])) {
            $limit = $param['limit'];
        }
        if (isset($param['page']) && !empty($param['page'])) {
            $start = ($param['page'] - 1) * $limit;
        }
        $userCouponModel = new  UserCoupon();

        if (isset($param['status']) && !empty($param['status'])) {
            $where[] = ['status','=',$param['status']];

        }else{
            $where[] = ['status','=',1];
        }
        if (isset($param['classify_id']) && !empty($param['classify_id'])) {
            $where[] = ['classify_id', 'in', [0, $param['classify_id']]];
        }
        $where[] =['uid','=',$request->userInfo['id']];
        $userCoupon = $userCouponModel->where($where)->limit($start, $limit)->select()->toArray();

        $count = $userCouponModel->where($where)->count();
        $couponId = array_column($userCoupon, 'coupon_id');
        $couponModel = new  CouponModel();
        $couponList = $couponModel->where('id', 'in', $couponId)->select()->toArray();
        $couponListById = array_column($couponList, null, 'id');
        foreach ($userCoupon as $key => $value) {
            $userCoupon[$key]['coupon_name'] = $couponListById[$value['coupon_id']]['name'];
            $userCoupon[$key]['type'] = $couponListById[$value['coupon_id']]['type'];
            $userCoupon[$key]['desc'] = $couponListById[$value['coupon_id']]['desc'];
            $userCoupon[$key]['effective_time'] = date('Y-m-d H:i:s', $value['effective_time']);
        }
        return success('我的优惠券', ['list' => $userCoupon, 'count' => $count]);
    }
}